package com.liheng.intcpt;

import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Li
 * 2017/8/9.
 * 拦截器
 * 业务含义：计算每一次请求的时间
 */

public class DemoInterceptor extends HandlerInterceptorAdapter {//1.继承此类来时间自定义拦截器

    //在请求发生前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        return true;
    }

    //在请求完成后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (long) request.getAttribute("startTime");
        long endTIme = (long) System.currentTimeMillis();
        System.out.println("本次请求处理时间为：" + new Long(endTIme - startTime) + "ms");
        request.setAttribute("handingTime", endTIme - startTime);
    }

}
